import { useEffect } from 'react'
import { Dropdown, Badge, Space, Avatar, type MenuProps } from 'antd'
import { BellOutlined } from '@ant-design/icons'
import { useAppDispatch, type RootState } from '@/store'
import { useSelector } from 'react-redux'
import { getRemindAction, setInfo, type Info } from '@/store/modules/news'
import { clearToken } from '@/store/modules/users'
import { Link } from 'react-router-dom'
import styles from '../index.module.scss'

const HomeHeader = () => {
  const { head, name, _id } = useSelector(
    (state: RootState) => state.users.infos
  )
  const newsInfo = useSelector((state: RootState) => state.news.info)
  const dispatch = useAppDispatch()
  const isDot =
    ((newsInfo.applicant || newsInfo.appover) as boolean) || undefined

  useEffect(() => {
    dispatch(getRemindAction({ userid: _id })).then((action) => {
      const { payload } = action
      const { errcode, info } = payload
      if (errcode === 0) {
        dispatch(setInfo(info as Info))
      }
    })
  }, [dispatch, _id])

  const handleLogut = () => {
    dispatch(clearToken())
    setTimeout(() => {
      window.location.replace('/login')
    })
  }

  const items1: MenuProps['items'] = []
  if (newsInfo.applicant) {
    items1.push({
      key: '1',
      label: <Link to="/apply">有审批结果消息</Link>,
    })
  }
  if (newsInfo.approver) {
    items1.push({
      key: '2',
      label: <Link to="/check">有审批请求消息</Link>,
    })
  }
  if (!newsInfo.applicant && !newsInfo.approver) {
    items1.push({
      key: '3',
      label: <div>暂无消息</div>,
    })
  }
  const items2: MenuProps['items'] = [
    {
      key: '1',
      label: <div>个人中心</div>,
    },
    {
      key: '2',
      label: <div onClick={handleLogut}>退出</div>,
    },
  ]

  return (
    <div className={styles['home-header']}>
      <span className={styles['home-header-logo']}>
        <i className={`iconfont icon-react ${styles['icon-react']}`}></i>
        <i
          className={`iconfont icon-icon-test ${styles['icon-icon-test']}`}
        ></i>
        <i
          className={`iconfont icon-typescript' ${styles['icon-typescript']}`}
        ></i>
      </span>
      <span className={styles['home-header-title']}>在线考勤系统</span>
      <Dropdown menu={{ items: items1 }} arrow placement="bottom">
        <Badge dot={isDot}>
          <BellOutlined style={{ fontSize: 20 }} />
        </Badge>
      </Dropdown>
      <Dropdown menu={{ items: items2 }} arrow placement="bottom">
        <Space className={styles['home-header-space']}>
          <Avatar src={head} size="large" /> {name}
        </Space>
      </Dropdown>
    </div>
  )
}

export default HomeHeader
